package codingforgreat.lchot150;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Lc103 {
  public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        if(root == null){
            return ans;
        }
        queue.add(root);
        boolean isHead = true;
        while(!queue.isEmpty()){
            int size = queue.size();
            ArrayList<Integer> res = new ArrayList<>();
            for(int i = 0;i < size;i++){
                TreeNode cur = isHead ? queue.pollFirst() : queue.pollLast();
                res.add(cur.val);
                if(isHead){
                    if(cur.left != null){
                        queue.addLast(cur.left);
                    }
                    if(cur.right != null){
                        queue.addLast(cur.right);
                    }
                }else{
                    if(cur.right != null){
                        queue.addFirst(cur.right);
                    }
                    if(cur.left != null){
                        queue.addFirst(cur.left);
                    }
                }
            }
            ans.add(res);
            isHead = !isHead;
        }
        return ans;
    }
}
